package com.lhj.security.controller;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.lhj.security.config.security.UserAuthDetail;
import com.lhj.security.service.ILoginService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author lhj
 * @Date 2024/12/25 14:54
 */
@Slf4j
@RestController
public class LoginController {
    
    @Resource
    private ILoginService loginService;
    
    @GetMapping("/login")
    public ResponseEntity<String> login(String username, String password) throws JsonProcessingException {
        String token = loginService.doLogin(username, password);
        if (token == null) {
            Map<String, Object> resultMap = Maps.newHashMap();
            resultMap.put("code", HttpStatus.UNAUTHORIZED.value());
            resultMap.put("info", HttpStatus.UNAUTHORIZED.getReasonPhrase());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new ObjectMapper().writeValueAsString(resultMap));
        }
        Map<String, Object> resultMap = Maps.newHashMap();
        resultMap.put("code", HttpStatus.OK.value());
        resultMap.put("data", token);
        return ResponseEntity.status(HttpStatus.OK).body(new ObjectMapper().writeValueAsString(resultMap));
    }
    
    @GetMapping("/userInfo")
    public ResponseEntity<?> userInfo() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        UserAuthDetail userAuthDetail = (UserAuthDetail) authentication.getPrincipal();
        JSONObject json = new JSONObject();
        json.put("username", userAuthDetail.getUsername());
        Collection<? extends GrantedAuthority> authorities = userAuthDetail.getAuthorities();
        List<String> roles = authorities.stream().map(GrantedAuthority::getAuthority).toList();
        json.put("authority", roles);
        return ResponseEntity.ok(json.toString());
    }
    
}
